import hashlib
import pickle
import re
from datetime import date
import gzip
import pyAesCrypt
from common import file_mgmt


# encryption/decryption buffer size - 64K


class Bin_storage:
    def __init__(self):
        pass

    def save_bare(self, name, dic):
        with open(name + '.bin', 'wb') as handle:
            pickle.dump(dic, handle, protocol=pickle.HIGHEST_PROTOCOL)
    def save(self, name, dic):
        with open('aes.tmp', 'wb') as handle:
            module = re.search('/([\w]+)/bin/[\d-]{10}$', name).group(1)
            code_name = self.read("/home/ubuntu/f10_serverside/code_name.pkl")
            try:
                if module == 'f11':
                    keys = list(dic.keys())
                    for code in keys:
                        if code in code_name:
                            i = code_name[code]
                            l = dic.pop(code)
                            l.reverse()
                            dic[i] = l
                        else:
                            dic.pop(code)
                else:
                    keys = list(dic.keys())
                    for code in keys:
                        if code in code_name:
                            dic[code_name[code]] = dic.pop(code)
                        else:
                            dic.pop(code)

            except Exception as e:
                print('Error occurs when applying name to dic:')
                print(str(e))
            pickle.dump(dic, handle, protocol=pickle.HIGHEST_PROTOCOL)
        # compress file
        f_in = open('aes.tmp', 'rb')
        f_out = gzip.open('aes.gz', 'wb')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        # encrypt file
        bufferSize = 64 * 1024
        password = hashlib.sha1(bytearray(str(date.today()), 'utf8')).hexdigest()
        pyAesCrypt.encryptFile('aes.gz', name + '.a', password, bufferSize)


        return file_mgmt.push(re.search('^(.+)/[^/]+$', name).group(1), ext="a")

    def read(self, path):
        with open(path, 'rb') as handle:
            in_dict = pickle.load(handle)
            return in_dict


if __name__ == '__main__':
    bin = Bin_storage()

    # d = bin.read('bin/2019-06-13.bin')
    d = bin.read('/home/ubuntu/f10_serverside/f10/bin/2019-06-22.bin')
    print(d)
